package com.th.therp.service.Impl;

import com.th.therp.exception.BaseException;
import com.th.therp.mapper.VendorMapper;
import com.th.therp.pojo.emtity.Vendor;
import com.th.therp.service.VendorService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class VendorServiceImpl  implements VendorService {

    @Autowired
    private VendorMapper vendorMapper;

    @Override
    public List<Vendor> list() {
        return vendorMapper.list();
    }

    @Override
    public void add(Vendor vendor) {
        Vendor existingVendor = vendorMapper.findByName(vendor.getName());
        if (existingVendor == null) {
            vendorMapper.add(vendor);
        }else {
            throw new BaseException("该供应商已存在");
        }
    }

    @Override
    public void update(Vendor vendor) {
        Vendor existingVendor = vendorMapper.findByName(vendor.getName());
        if (existingVendor != null && !existingVendor.getId().equals(vendor.getId())) {
            throw new BaseException("该供应商已存在");
        }else {
            vendorMapper.update(vendor);
        }
    }

    @Override
    public void delete(List<Integer> ids) {
        ids.forEach(id -> {
            Vendor vendor = Vendor.builder()
                    .id(id)
                    .isDeleted(1)
                    .build();
           vendorMapper.update(vendor);
        });
    }

    @Override
    public String findNameById(Integer vendorId) {
        return vendorMapper.findNameById(vendorId);
    }
}
